package com.changgou.controller;

import com.alibaba.fastjson.JSON;
import com.changgou.service.WeixinPayService;
import com.github.wxpay.sdk.WXPayUtil;
import entity.Result;
import entity.StatusCode;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ：hushengjin
 */

@RestController
@RequestMapping("/weixin/pay")
@CrossOrigin
public class WeixinPayController {

    @Value("${mq.pay.exchange.order}")
    private String exchange;

    @Value("${mq.pay.queue.order}")
    private String queue;

    @Value("${mq.pay.routing.key}")
    private String routing;

    @Autowired
    private WeixinPayService weixinPayService;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 支付回调
     *
     * @param request
     * @return
     */
    @RequestMapping("/notify/url")
    public String notifyUrl(HttpServletRequest request) {
        InputStream inputStream;
        //读取回调数据
        try {
            inputStream = request.getInputStream();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len;
            while((len = inputStream.read(buffer)) != -1) {
                byteArrayOutputStream.write(buffer, 0, len);
            }

            byteArrayOutputStream.close();
            inputStream.close();
            //将支付信息转成xml字符串
            String xmlStr = new String(byteArrayOutputStream.toByteArray(), "UTF-8");
            //将xml字符串转换成map集合
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xmlStr);

            //获取附加信息
            Map<String, String> attach = JSON.parseObject(resultMap.get("attach"), Map.class);
            //将消息发送给mq消息队列
            rabbitTemplate.convertAndSend(exchange, attach.get("queue"), JSON.toJSONString(resultMap));

            //设置响应数据
            Map respMap = new HashMap();
            respMap.put("return_code","SUCCESS");
            respMap.put("return_msg","OK");
            return WXPayUtil.mapToXml(respMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 创建二维码
     *
     * @param params
     * @return
     */
    @RequestMapping("/create/native")
    public Result createNative(@RequestParam Map<String, String> params) {
        Map map = weixinPayService.createNative(params);
        return new Result(true, StatusCode.OK, "创建二维码成功", map);
    }

    /**
     * 查询订单信息
     *
     * @param out_trade_no
     * @return
     */
    @RequestMapping("/query/status")
    public Result queryStatus(String out_trade_no) {
        Map map = weixinPayService.queryPayStatus(out_trade_no);
        return new Result(true, StatusCode.OK, "查询成功", map);
    }

    /**
     * 关闭订单
     *
     * @param orderId
     * @return
     */
    @RequestMapping("/close/pay")
    public Result closePay(Long orderId) {
        Map<String, String> stringStringMap = weixinPayService.closePay(orderId);
        return new Result(true, StatusCode.OK, "关闭成功", stringStringMap);
    }
}
